<template>
  <form class="validate-form-container">
    <!-- 默认slot -->
    <slot></slot>
    <!-- 监听点击事件，点击事件触发sumitForm函数 -->
    <div class="submit-area clear" @click.prevent="sumitForm">
      <slot name="submit">
        <button type="sumit" class="btn btn-primary form-btn">提交</button>
      </slot>
    </div>
  </form>
</template>
<script lang="ts">
import { defineComponent, onUnmounted } from "vue";
import mitt from "mitt";
type validateFunc = () => boolean;
// 一个页面上有两个validateForm怎么搞
export const emitter = mitt();
export default defineComponent({
  name: "ValidateForm",
  emits: ["form-sumit"],
  setup(props, context) {
    let funcArr: validateFunc[] = [];

    // 发布订阅模式
    const callback = (func?: validateFunc) => {
      if (func) {
        funcArr.push(func);
      }
    };
    emitter.on("form-item-created", callback);
    const sumitForm = () => {
      // map起到循环遍历的作用
      const result = funcArr.map((func) => func()).every((result) => result);
      // 触发form-sumit事件，将funcArr遍历的结果返回ture/false
      context.emit("form-sumit", result);
    };
    onUnmounted(() => {
      emitter.off("form-item-created", callback);
      funcArr = [];
    });
    return {
      sumitForm,
    };
  },
});
</script>
<style lang="scss" scoped>
.form-btn {
  float: right;
}
</style>
